package com.st.buy.cart.interceptors;

import com.st.buy.pojo.TbUser;
import com.st.buy.util.pojo.BuyResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 张双虎
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RestTemplate restTemplate;

    @Value("${ssoService}")
    private String ssoService;
    @Value("${ssoURL}")
    private String ssoURL;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //取出cookie中token
        Cookie[] cookies = request.getCookies();
        if(cookies!=null){
            String token = null;
            for(Cookie cookie : cookies){
                if(cookie.getName().equals("TOKNE")){
                    token = cookie.getValue();
                    break;
                }
            }
            if(token!=null){
                //cookie中的token存在
                //进行远程调用查询用户信息
                BuyResult result = restTemplate.getForObject("http://" + ssoService + "/user/checktoken/" + token, BuyResult.class);
                //判断状态码
                if(result.getStatus()==200){
                    //登录成功
                    //将用户信息设置到request中。
                    request.setAttribute("loginUser",result.getData());
                    //放行
                    return true;
                }
            }
        }
        //拦截
        //冲定向到登录页面 携带当前请求的url
        String url = request.getRequestURL().toString();
        response.sendRedirect(ssoURL+"login?redirect="+url+"?num="+request.getParameter("num"));
        return false;
    }
}
